{% extends "menu.html" %}
{% block title %}个人主页{% endblock %}
{% block content %}
<html lang="zh">
<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人主页</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        h1, h2 {
            color: #333;
        }
        #profile, form, #termCollections {
            background-color: white;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        input[type="file"], input[type="text"], button {
            margin: 10px 0;
            padding: 10px;
            width: 100%;
            box-sizing: border-box;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .term-collection {
            background-color: #f9f9f9;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
        }
        .delete-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            float: right;
        }
    </style>
</head>

<body>
    <h1>个人主页</h1>
    <div id="profile">
        <!-- 用户信息将显示在这里 -->
    </div>

    <h2>上传术语库</h2>
    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" name="file" accept=".csv,.xlsx" required>
        <input type="text" name="table_name" placeholder="术语表名称" required>
        <input type="text" name="category" placeholder="分类" required>
        <button type="submit">上传</button>
    </form>

    <h2>我的术语集</h2>
    <div id="termCollections">
        <!-- 术语集列表将在这里显示 -->
    </div>

    <script>
        console.log('Profile script running');
        const token = localStorage.getItem('jwtToken');
        console.log('Token retrieved:', token);

        if (!token) {
            window.location.href = '/login';
        } else {
            // 验证 JWT token
            fetch('/verify_token', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Token 验证失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.valid) {
                    fetchUserProfile();
                    fetchTermCollections();
                } else {
                    throw new Error('Token 无效');
                }
            })
            .catch(error => {
                console.error('Token 验证失败:', error);
                localStorage.removeItem('jwtToken');
                window.location.href = '/login';
            });
        }

        function fetchUserProfile() {
            fetch('/access_profile', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                const profileDiv = document.getElementById('profile');
                profileDiv.innerHTML = `
                    <p><strong>昵称：</strong> ${data.nickname}</p>
                    <p><strong>邮箱：</strong> ${data.email}</p>
                `;
            })
            .catch(error => {
                console.error('请求失败:', error);
            });
        }

        function fetchTermCollections() {
            fetch('/get_user_term_collections', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(data => {
                const termCollectionsDiv = document.getElementById('termCollections');
                termCollectionsDiv.innerHTML = '';
                data.forEach(collection => {
                    const collectionDiv = document.createElement('div');
                    collectionDiv.className = 'term-collection';
                    collectionDiv.innerHTML = `
                        <span>${collection.table_name}</span>
                        <button class="delete-btn" onclick="deleteTermCollection(${collection.id})">删除</button>
                    `;
                    termCollectionsDiv.appendChild(collectionDiv);
                });
            })
            .catch(error => {
                console.error('获取术语集失败:', error);
            });
        }

        function deleteTermCollection(collectionId) {
            if (confirm('确定要删除这个术语集吗？')) {
                fetch(`/delete_term_collection/${collectionId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    fetchTermCollections(); // 重新加载术语集列表
                })
                .catch(error => {
                    console.error('删除术语集失败:', error);
                    alert('删除失败，请重试');
                });
            }
        }

        document.getElementById('uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);

            fetch('/upload_term_collection', {
                method: 'POST',
                body: formData,
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                fetchTermCollections(); // 刷新术语集列表
            })
            .catch(error => {
                console.error('上传失败:', error);
                alert('上传失败，请重试');
            });
        });
    </script>
</body>
</html>
{% endblock %}